import Store from "@/store/index"
import BasicConfig from "@/utils/config"
/**
 * @description 删除图片(图片上传组件)
 */
export const useDeletePic = (event, list) => {
	list.splice(event.index, 1)
	return list;
}

/**
 * @description 选择图片
 */
export const useAfterRead = async (event, fileList) => {
	return new Promise(async (resovle, reject) => {
		// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file)
		let fileListLen = fileList.length
		lists.map((item) => {
			fileList.push({
				...item,
				status: 'uploading',
				message: '上传中'
			})
		})
		for (let i = 0; i < lists.length; i++) {
			const result = await useUploadFilePromise(lists[i].url, {
				bs: '2'
			})
			let item = fileList[fileListLen]
			fileList.splice(fileListLen, 1, Object.assign(item, {
				status: 'success',
				message: '',
				// url: result,
				file: result
			}))
			fileListLen++
		}
		resovle({
			data: fileList
		})
	})
}

/**
 * @description 文件上传 
 * @param {String} url 文件路径
 * @param {Object} formData
 */
export const useUploadFilePromise = (url, formData) => {
	const token = Store.state.user.token;
	return new Promise((resolve, reject) => {
		let a = uni.uploadFile({
			url: BasicConfig.uploadUrl,
			filePath: url,
			name: 'file',
			formData,
			header: {
				Authorization: token,
				token
			},
			success: (uploadRes) => {
				const response = JSON.parse(uploadRes.data)
				setTimeout(() => {
					resolve(response)
				}, 1000)
			}
		});
	})
}
